using Godot;
using System;
using System.Collections.Generic;

public partial class LevelStateMachime : Node
{

    public BaseLevelManager LevelManager { get; private set; }

    Dictionary<string, BaseLevelState> states = new();

    public override void _Ready()
    {
        base._Ready();
        GetChildStates();
        LevelManager = GetParent<BaseLevelManager>();
    }

    private void GetChildStates()
    {
        foreach (var node in GetChildren())
        {
            if (node is BaseLevelState state)
            {
                states.Add(state.Name.ToString().ToLower(), state);
                state.OnStateEnd += OnStateEndHandler;
            }
        }
    }

    public void RunState(string stateName)
    {
        stateName = stateName.ToLower();
        GD.Print("下一个状态： ", stateName);
        if (!states.ContainsKey(stateName)) return;
        currentState?.Exit();
        currentState = states[stateName];
        currentState.Enter();

    }

    private void OnStateEndHandler(BaseLevelState state)
    {
        // 开屏画面完成直接开始下一回合
        if (state.Name.ToString().ToLower() == "levelstartscreenstate")
        {
            LevelManager.NextRound();
            return;
        }
        var stateName = LevelManager.GetStateName().ToLower();
        GD.Print("下一个状态： ", stateName);
        var newState = states[stateName];
        if (newState == null) return;
        currentState?.Exit();
        currentState = newState;
        currentState.Enter();
    }

    BaseLevelState currentState;

}
